package edu.gatech.angry12.domain;

import java.util.ArrayList;

import javax.persistence.TypedQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

/**
 * The listener interface for receiving authenticationFailure events.
 * The class that is interested in processing a authenticationFailure
 * event implements this interface, and the object created
 * with that class is registered with a component using the
 * component's <code>addAuthenticationFailureListener<code> method. When
 * the authenticationFailure event occurs, that object's appropriate
 * method is invoked.
 *
 * @see AuthenticationFailureEvent
 */
@Component 
public class AuthenticationFailureListener  
    implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> { 
 
  //@Autowired 
  /** The user. */
  private User user; 
 
  /* (non-Javadoc)
   * @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
   */
  public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent ev) { 
 
    String username = ev.getAuthentication().getName(); 
 
    user = User.findUsersByNameEquals(username).getSingleResult();
    	System.out.println(user.getUserName());
    
    if (user != null) { // only for existing users 
    	int numFailures;    
    	if (user.getLoginTries() != null)
            numFailures = user.getLoginTries();
    	else
    		numFailures = 0;
            System.out.println(numFailures);
            if (numFailures == 2) {
            	user.setLoginTries(0);
            	user.setEnabled(false);
            }
            else {
          		 user.setLoginTries(numFailures+1);
            }
            user.merge(); 
    } 
  } 
} 

